package juc;

import org.junit.Test;

import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class CountDownLatchTest {

	private final AtomicInteger poolNumber = new AtomicInteger(1);

	/**
	 * 定义一个线程池
	 */
	private ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 50, 60, TimeUnit.SECONDS,
			new LinkedBlockingDeque<>(2000), r -> new Thread(r,"工人" + poolNumber.incrementAndGet()));

	class Worker implements Runnable{

		private CountDownLatch countDownLatch;

		Worker(CountDownLatch countDownLatch) {
			this.countDownLatch = countDownLatch;
		}

		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName() + "开始执行任务");
			try {
				Thread.sleep(new Random().nextInt(10000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "执行任务结束");
			countDownLatch.countDown();
		}
	}

	@Test
	public void testCountDownLatch() {
		CountDownLatch countDownLatch = new CountDownLatch(5);
		for (int i = 0; i < 5; i++) {
			executor.execute(new Worker(countDownLatch));
		}
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("任务全部执行结束");
	}


}
